import { defineStore } from 'pinia'
import { ref, onMounted, onUnmounted } from 'vue'

interface AdData {
  date: string
  value: number
}

export const useAdStore = defineStore('ad', () => {
  const realtimeExposureData = ref<AdData[]>([])
  const hourlyExposureData = ref<AdData[]>([])
  const dailyExposureData = ref<AdData[]>([])
  const realtimeClickData = ref<AdData[]>([])
  const hourlyClickData = ref<AdData[]>([])
  const dailyClickData = ref<AdData[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  const getCurrentExposureData = (timeRange: string) => {
    switch (timeRange) {
      case 'realtime': return realtimeExposureData.value
      case 'hourly': return hourlyExposureData.value
      case 'daily': return dailyExposureData.value
      default: return []
    }
  }

  const getCurrentClickData = (timeRange: string) => {
    switch (timeRange) {
      case 'realtime': return realtimeClickData.value
      case 'hourly': return hourlyClickData.value
      case 'daily': return dailyClickData.value
      default: return []
    }
  }

  let refreshTimer: number | null = null

  const fetchData = async (timeRange = 'realtime') => {
    loading.value = true
    error.value = null

    try {
      const response = await fetch(`http://localhost:3002/api/ads?range=${timeRange}`)

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()

      if (timeRange === 'realtime') {
        realtimeExposureData.value = data.exposure || []
        realtimeClickData.value = data.clicks || []
      } else if (timeRange === 'hourly') {
        hourlyExposureData.value = data.exposure || []
        hourlyClickData.value = data.clicks || []
      } else {
        dailyExposureData.value = data.exposure || []
        dailyClickData.value = data.clicks || []
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取数据失败'
      console.error('Failed to fetch data:', err)

      // 设置空数组避免组件错误
      if (timeRange === 'realtime') {
        realtimeExposureData.value = []
        realtimeClickData.value = []
      } else if (timeRange === 'hourly') {
        hourlyExposureData.value = []
        hourlyClickData.value = []
      } else {
        dailyExposureData.value = []
        dailyClickData.value = []
      }
    } finally {
      loading.value = false
    }
  }

  const startAutoRefresh = (interval = 5000) => {
    stopAutoRefresh() // 确保没有重复的定时器
    refreshTimer = window.setInterval(() => fetchData(), interval)
  }

  const stopAutoRefresh = () => {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }

  onMounted(() => {
    fetchData()
    startAutoRefresh()
  })

  onUnmounted(() => {
    stopAutoRefresh()
  })

  return {
    realtimeExposureData,
    hourlyExposureData,
    dailyExposureData,
    realtimeClickData,
    hourlyClickData,
    dailyClickData,
    loading,
    error,
    getCurrentExposureData,
    getCurrentClickData,
    fetchData,
    startAutoRefresh,
    stopAutoRefresh
  }
})
